//
//  SearchBar.swift
//  myhub
//
//  Created by x on 2024/5/26.
//

import UIKit
import XResources
import XDesignKit

open class SearchBar: UISearchBar {
    public override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
    }

    open func makeUI() {
        placeholder = R.string.localizable.commonSearch.key.localized()
        isTranslucent = false
        searchBarStyle = .minimal

        theme.tintColor = themeService.attribute { $0.secondary }
        theme.barTintColor = themeService.attribute { $0.primaryDark }

        if let textField = textField {
            textField.theme.textColor = themeService.attribute { $0.text }
            textField.theme.keyboardAppearance = themeService.attribute { $0.keyboardAppearance }
        }
        /// [weak self] 是捕获列表，用于定义闭包内部对外部对象的捕获方式，
        /// ( )  是闭包的参数列表，这里是一个空参数列表
        rx.textDidBeginEditing.asObservable().subscribe(onNext: { [weak self]
            () in
            self?.setShowsCancelButton(true, animated: true)
        }).disposed(by: rx.disposeBag)

        rx.textDidEndEditing.asObservable().subscribe(onNext: { [weak self]
            () in
            self?.setShowsCancelButton(false, animated: true)
        }).disposed(by: rx.disposeBag)

        rx.cancelButtonClicked.asObservable().subscribe(onNext: { [weak self]
            () in
            self?.resignFirstResponder()
        }).disposed(by: rx.disposeBag)

        rx.searchButtonClicked.asObservable().subscribe(onNext: { [weak self]
            () in
            self?.resignFirstResponder()
        }).disposed(by: rx.disposeBag)

        updateUI()
    }

    open func updateUI() {
        setNeedsDisplay()
    }
}
